package com.pratices.requestAndResponse.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pratices.requestAndResponse.bean.LoginUser;
import com.pratices.requestAndResponse.mapper.LoginUserMapper;
import com.pratices.requestAndResponse.utils.MybatisUtils;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.Map;

@WebServlet("/auth/login")
public class AuthLoginServlet extends HttpServlet {
    static LoginUserMapper loginUserMapper;
    static SqlSession sqlSession;
    static {
        sqlSession = MybatisUtils.getSqlConnection();
        loginUserMapper = sqlSession.getMapper(LoginUserMapper.class);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        BufferedReader reader = req.getReader();

        //获取请求体
        String jsonStr = reader.lines().reduce("", (acc, cur) -> acc + cur);

        System.out.println("jsonStr = " + jsonStr);
        /*        调试信息
        System.out.println("Content-Type: " + req.getContentType());
       System.out.println("Content-Length: " + req.getContentLength());*/
        //把JSON字符串转换为对象
        ObjectMapper objectMapper = new ObjectMapper();
        LoginUser loginUser = objectMapper.readValue(jsonStr, LoginUser.class);
        //调用数据库，插入数据
        int insertLoginUser = loginUserMapper.insertLoginUser(loginUser);
        if (insertLoginUser > 0) {
            //返回成功
            resp.getWriter().write("{\"code\":200,\"msg\":\"success\"}");
        } else {
            //返回失败
            resp.getWriter().write("{\"code\":500,\"msg\":\"fail\"}");
        }
    }
}
